package net.rock.service;

import net.rock.mapper.OrderMapper;
import net.rock.pojo.Order;
import net.rock.pojo.OrderBook;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    private void integrateOrderBook(Order order) {
        List<OrderBook> orderBooks = orderMapper.fetchOrderBookByOrderId(order.getId());
        order.setBooks(orderBooks);
    }

    public List<Order> fetchAllOrders() {
        List<Order> orders = orderMapper.fetchAllOrders();

        orders.forEach(this::integrateOrderBook);

        return orders;
    }

    public List<Order> fetchOrdersByUserId(int userId) {
        List<Order> orders = orderMapper.fetchOrdersByUserId(userId);

        orders.forEach(this::integrateOrderBook);

        return orders;
    }

    public void add(Order order) {
        Date now = new Date();
        String id = DigestUtils.md5Hex(String.format("%d%s", order.getUserId(), now));
        List<OrderBook> books = order.getBooks();
        order.setId(id);
        order.setOrderTime(now);
        order.setStatus(0);

        orderMapper.add(order);
        for (OrderBook orderBook: books) {
            orderMapper.insertOrderBook(id, orderBook.getBookId(), orderBook.getCnt());
        }
    }

    public void del(String id) {
        orderMapper.delOrderBooks(id);
        orderMapper.delOrder(id);
    }

    public void pay(String id) {
        orderMapper.pay(id);
    }

    public void send(String id) {
        orderMapper.send(id);
    }

    public void confirm(String id) {
        orderMapper.confirm(id);
    }
}
